package com.example.boot.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户及权限设置
 */
@Configuration
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;


    /**
     * 加载用户
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //com.grf.pojo.User user = userService.getUserByUsername(username);

        if (!username.equals("grf")) {
            throw new UsernameNotFoundException("用户不存在");
        }

        String myPassword = passwordEncoder.encode("1");


        Collection<GrantedAuthority> authorities = authorities();
        return new User(username, myPassword, authorities);
    }

    /**
     * 给用户授权
     * @return 权限列表
     */
    private Collection<GrantedAuthority> authorities() {
        List<GrantedAuthority> authority = new ArrayList();
        authority.add(new SimpleGrantedAuthority("test1"));
        authority.add(new SimpleGrantedAuthority("test2"));
        return authority;
    }

}
